﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LCA.Community.DAL.Model;
using System.IO;
using Microsoft.Win32;
using Microsoft.WindowsAzure;
using LCA.Community.DAL.Interfaces;

namespace LCA.Community.DAL.Test.ModelFactories
{
    public class AvatarsFactory
    {
        private int count = 0;
        private Uri _baseUrl;

        public AvatarsFactory(Uri baseUrl)
        {
            _baseUrl = baseUrl;
        }

        public Avatar CreateEntity(string userName, string image)
        {
            var fileInfo = new FileInfo(image);
            var contentType = GetMimeType(fileInfo);
            var stream = File.OpenRead(image);

            var avatar = new Avatar(
                                userName,
                                new Uri(String.Format("{0}/{1}",_baseUrl.AbsoluteUri,userName)),
                                contentType,
                                stream,
                                "testavatars"
                            );
            count++;

            return avatar;
        }

        private string GetMimeType(FileInfo fileInfo) 
        { 
            string mimeType = "application/unknown"; 
            RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(fileInfo.Extension.ToLower()); 
            if (regKey != null) 
            { 
                object contentType = regKey.GetValue("Content Type"); 
                if (contentType != null)                
                    mimeType = contentType.ToString(); 
            } 
            
            return mimeType; 
        }

        public List<Avatar> CreateList(List<User> users, string image)
        {
            var avatars = new List<Avatar>();

            foreach (var user in users)
            {
                avatars.Add(CreateEntity(user.Alias,image));
            }

            return avatars;
        }
    }
}
